import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type { loginFormData, loginResponseData, userResponseData } from '@/api/user/type'
import type { UserState } from './types/types'
import { setToken, getToken, removeToken } from '@/utils/auth'
import { constantRoute, asyncRoute, anyRoute } from '@/router/routes'
import router from '@/router'
import { filterAsyncRoute } from '@/utils/utils'
import { cloneDeep } from 'lodash'

const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      // 保证pinia中的token是持久化的
      token: getToken(),
      menuRoutes: constantRoute,
      avatar: '',
      username: '',
      buttons: [],
    }
  },
  actions: {
    async userLogin(loginForm: loginFormData) {
      const res: loginResponseData = await reqLogin(loginForm)
      if (res.code === 200) {
        this.token = res.data
        setToken(this.token)
        return 'ok'
      } else {
        return Promise.reject(new Error(res.data))
      }
    },
    async userInfo() {
      const res: userResponseData = await reqUserInfo()
      if (res.code === 200) {
        // 路由加载
        const routes = res.data.routes
        // 菜单需要的数据（路由中还没注册）
        const userAsyncRoute: any[] = filterAsyncRoute(cloneDeep(asyncRoute), routes)
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, ...anyRoute]
        // 注册路由（通用路由一开始以及注册到router中了，这里不需要在注册了）
        ;[...userAsyncRoute, anyRoute].forEach((item: any) => {
          router.addRoute(item)
        })

        // 按钮权限
        this.buttons = res.data.buttons
        this.avatar = res.data.avatar
        this.username = res.data.name
        localStorage.setItem('curUserName', this.username)
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    async useLogout() {
      const res: any = await reqLogout()
      if (res.code === 200) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        this.menuRoutes = []
        removeToken()
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
  },
  getters: {},
})

export default useUserStore
